﻿
namespace WordBibliographyAddin
{
    using System;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;
    using bibtex.dom;
    using bibtex.parser;
    using Microsoft.Office.Tools.Ribbon;

    public partial class BibliographyRibbon
    {
        private void BibliographyRibbon_Load(object sender, RibbonUIEventArgs e)
        {


            btnAddStyle.Label = Utils.TranslateText(btnAddStyle.Label);
            btnAddStyle.Description = Utils.TranslateText(btnAddStyle.Description);
            btnAddStyle.SuperTip = Utils.TranslateText(btnAddStyle.SuperTip);
            btnAddStyle.ScreenTip = Utils.TranslateText(btnAddStyle.ScreenTip);

            btnEditStyle.Label = Utils.TranslateText(btnEditStyle.Label);
            btnEditStyle.Description = Utils.TranslateText(btnEditStyle.Description);
            btnEditStyle.SuperTip = Utils.TranslateText(btnEditStyle.SuperTip);
            btnEditStyle.ScreenTip = Utils.TranslateText(btnEditStyle.ScreenTip);

            btnImportSources.Label = Utils.TranslateText(btnImportSources.Label);
            btnImportSources.Description = Utils.TranslateText(btnImportSources.Description);
            btnImportSources.SuperTip = Utils.TranslateText(btnImportSources.SuperTip);
            btnImportSources.ScreenTip = Utils.TranslateText(btnImportSources.ScreenTip);

            btnExportSources.Label = Utils.TranslateText(btnExportSources.Label);
            btnExportSources.Description = Utils.TranslateText(btnExportSources.Description);
            btnExportSources.SuperTip = Utils.TranslateText(btnExportSources.SuperTip);
            btnExportSources.ScreenTip = Utils.TranslateText(btnExportSources.ScreenTip);

            grpStyles.Label = Utils.TranslateText(grpStyles.Label);
            grpSources.Label = Utils.TranslateText(grpSources.Label);

            btnAddStyle.Enabled = Utils.HasAdminPrivileges();
            btnEditStyle.Enabled = btnAddStyle.Enabled;


        }

        private void btnEditStyle_Click(object sender, RibbonControlEventArgs e)
        {
            btnEditStyle.Enabled = false;
            Application.DoEvents();

            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Title = Utils.TranslateText("Edit Bibliography Style");
                dlg.AddExtension = true;
                dlg.CheckFileExists = true;
                dlg.CheckPathExists = true;
                dlg.DefaultExt = "xsl";
                dlg.Filter = "XSL Files (*.xsl)|*.xsl";
                dlg.InitialDirectory = Utils.GetWordBibliographyStylesFolder();

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    using (XSLEditorForm form = new XSLEditorForm(dlg.FileName))
                    {
                        form.ShowDialog();
                    }
                }
            }
            btnEditStyle.Enabled = true;
            Application.DoEvents();
        }

        private string CleanText(string txt)
        {
            return txt.Replace("\n", "").Replace("\r", "").Replace("{", "").Replace("}", "");
        }

        private void btnImportSource_Click(object sender, RibbonControlEventArgs e)
        {
            //string temp = WordApplication.Instance.Bibliography.Sources[1].XML;

            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Title = Utils.TranslateText("Import Bibliography Sources");
                dlg.AddExtension = true;
                dlg.CheckFileExists = true;
                dlg.CheckPathExists = true;
                dlg.DefaultExt = "bib";
                dlg.Filter = "BibTeX Files (*.bib)|*.bib";
                dlg.InitialDirectory = Utils.GetWordBibliographyStylesFolder();

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    BibtexFile bibtexFile = new BibtexFile();
                    BibtexParser parser = new BibtexParser(false);
                    parser.parse(bibtexFile, dlg.FileName);

                    long count = 0;
                    java.util.List l = bibtexFile.getEntries();
                    for (int i = 0; i < l.size(); i++)
                    {

                        string strXml = "<b:Source xmlns:b=\"http://schemas.microsoft.com/office/word/2004/10/bibliography\">";
                        strXml += "<b:RefOrder>1</b:RefOrder>";
                        strXml += "<b:Guid>" + System.Guid.NewGuid().ToString("B").ToUpper() + "</b:Guid>";
                        strXml += "<b:LCID>0</b:LCID>";

                        BibtexNode node = (BibtexNode)l.get(i);
                        BibtexEntry entry = node as BibtexEntry;
                        if (entry != null)
                        {
                            BibtexAbstractValue value = null;
                            Random rd = new Random(80000);

                            strXml += "<b:Tag>Bib" + DateTime.Now.ToString("yyyyMMddHmmssff") + "</b:Tag>";

                            value = entry.getFieldValue("author");
                            if (value != null) strXml += "<b:Author><b:Author><b:NameList><b:Person><b:Last>" + CleanText(value.toString()) +
                                            "</b:Last><b:First></b:First></b:Person></b:NameList></b:Author></b:Author>";

                            value = entry.getFieldValue("title");
                            if (value != null) strXml += "<b:Title>" + CleanText(value.toString()) + "</b:Title>";

                            value = entry.getFieldValue("journal");
                            if (value != null) strXml += "<b:JournalName>" + CleanText(value.toString()) + "</b:JournalName>";

                            value = entry.getFieldValue("year");
                            if (value != null) strXml += "<b:Year>" + CleanText(value.toString()) + "</b:Year>";

                            value = entry.getFieldValue("month");
                            if (value != null) strXml += "<b:Month>" + CleanText(value.toString()) + "</b:Month>";

                            value = entry.getFieldValue("city");
                            if (value != null) strXml += "<b:City>" + CleanText(value.toString()) + "</b:City>";

                            value = entry.getFieldValue("publisher");
                            if (value != null) strXml += "<b:Publisher>" + CleanText(value.toString()) + "</b:Publisher>";
                            
                            value = entry.getFieldValue("volume");
                            if (value != null) strXml += "<b:Volume>" + CleanText(value.toString()) + "</b:Volume>";

                            value = entry.getFieldValue("review");
                            if (value != null) strXml += "<b:Issue>" + CleanText(value.toString()) + "</b:Issue>";

                            value = entry.getFieldValue("pages");
                            if (value != null) strXml += "<b:Pages>" + CleanText(value.toString()) + "</b:Pages>";

                            strXml += "<b:SourceType>JournalArticle</b:SourceType>";

                            strXml += "</b:Source>";

                            try
                            {

                                WordApplication.Instance.Bibliography.Sources.Add(strXml);
                                count++;
                            }
                            catch (Exception) { }

                        }


                    }

                    Utils.ShowKryptonDialog("Imported Sources", "A total of {0} bibliography sources are imported.", MessageBoxIcon.Information, count);
                }
            }

        }

        private void btnExportSources_Click(object sender, RibbonControlEventArgs e)
        {
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.Title = Utils.TranslateText("Export Bibliography Sources");
                dlg.AddExtension = true;

                dlg.CheckPathExists = true;
                dlg.DefaultExt = "bib";
                dlg.Filter = "BibTeX Files (*.bib)|*.bib";
                dlg.InitialDirectory = Utils.GetWordBibliographyStylesFolder();
                dlg.FileName = "bibliography-sources";
                dlg.OverwritePrompt = false;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    StringBuilder bd = new StringBuilder();

                    foreach (Microsoft.Office.Interop.Word.Source item in WordApplication.Instance.Bibliography.Sources)
                    {
                        string xml = item.XML;

                        int first = 0;
                        int last = 0;

                        first = xml.IndexOf("<b:Tag>");
                        last = xml.IndexOf("</b:Tag>");

                        bd.Append("@article{");

                        if (first != -1)
                            bd.AppendLine(xml.Substring(first + 7, last - first - 7) + ",");
                        else
                            bd.AppendLine(",");

                        first = xml.IndexOf("<b:Last>");
                        last = xml.IndexOf("</b:Last>");

                        if (first != -1)
                        {
                            string name = xml.Substring(first + 8, last - first - 8);

                            first = xml.IndexOf("<b:First>");
                            last = xml.IndexOf("</b:First>");

                            if (first != -1)
                                name += "," + xml.Substring(first + 9, last - first - 9);

                            bd.AppendLine("author = {" + name + "},");
                        }

                        first = xml.IndexOf("<b:Title>");
                        last = xml.IndexOf("</b:Title>");

                        if (first != -1)
                            bd.AppendLine("title = {" + xml.Substring(first + 9, last - first - 9) + "},");

                        first = xml.IndexOf("<b:JournalName>");
                        last = xml.IndexOf("</b:JournalName>");
                        if (first != -1)
                            bd.AppendLine("journal = {" + xml.Substring(first + 15, last - first - 15) + "},");

                        first = xml.IndexOf("<b:Month>");
                        last = xml.IndexOf("</b:Month>");
                        if (first != -1)
                            bd.AppendLine("month = {" + xml.Substring(first + 9, last - first - 9) + "},");

                        first = xml.IndexOf("<b:City>");
                        last = xml.IndexOf("</b:City>");
                        if (first != -1)
                            bd.AppendLine("city = {" + xml.Substring(first + 8, last - first - 8) + "},");

                        first = xml.IndexOf("<b:Year>");
                        last = xml.IndexOf("</b:Year>");
                        if (first != -1)
                            bd.AppendLine("year = {" + xml.Substring(first + 8, last - first - 8) + "},");

                        first = xml.IndexOf("<b:Publisher>");
                        last = xml.IndexOf("</b:Publisher>");
                        if (first != -1)
                            bd.AppendLine("publisher = {" + xml.Substring(first + 13, last - first - 13) + "},");

                        first = xml.IndexOf("<b:Volume>");
                        last = xml.IndexOf("</b:Volume>");
                        if (first != -1)
                            bd.AppendLine("volume = {" + xml.Substring(first + 10, last - first - 10) + "},");


                        first = xml.IndexOf("<b:Issue>");
                        last = xml.IndexOf("</b:Issue>");
                        if (first != -1)
                            bd.AppendLine("review = {" + xml.Substring(first + 9, last - first - 9) + "},");

                        first = xml.IndexOf("<b:Pages>");
                        last = xml.IndexOf("</b:Pages>");
                        if (first != -1)
                            bd.AppendLine("pages = {" + xml.Substring(first + 9, last - first - 9) + "},");

                        bd.AppendLine("},");

                    }

                    using (StreamWriter w = File.CreateText(dlg.FileName))
                    {
                        w.WriteLine(bd.ToString());
                    }
                    Utils.ShowKryptonDialog("Exported Sources", "A total of {0} bibliography sources are exported.", MessageBoxIcon.Information,
                        WordApplication.Instance.Bibliography.Sources.Count);
                }
            }

        }

        private void btnAddStyle_Click(object sender, RibbonControlEventArgs e)
        {
            btnAddStyle.Enabled = false;
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Title = Utils.TranslateText("Import Bibliography Style");
                dlg.AddExtension = true;
                dlg.CheckFileExists = true;
                dlg.CheckPathExists = true;
                dlg.DefaultExt = "xsl";
                dlg.Filter = "XSL Files (*.xsl)|*.xsl";
                dlg.InitialDirectory = Utils.GetWordBibliographyStylesFolder();

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    String newFile = Path.GetFileName(dlg.FileName);
                    newFile = Path.Combine(Utils.GetWordBibliographyStylesFolder(), newFile);
                    try
                    {
                        File.Copy(dlg.FileName, newFile, true);
                        Utils.ShowKryptonDialog("Restart Microsoft Word", "In order for your changes to take effect, please restart Microsoft Word.", MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        Utils.ShowKryptonDialog("An error has occurred", ex.Message, MessageBoxIcon.Error);
                    }
                }
            }
            btnAddStyle.Enabled = true;
        }
    }
}
